<?php
namespace Admin\Controller;
use Think\Controller;
use Think\Image;
class KeywordsController extends PublicController {


	function _initialize() {
		parent::_initialize ();
	}
	//代理商列表
    public function index(){
        $header = C('header')['keywords'];
        if(IS_POST){
            $data = I('post.');
            $keyword = trim($data['keyword']);

            $selectwhere['kwd'] = $keyword;
            $time = time()-120;
            $selectwhere['logtime'] = array('gt',$time);
            $select = M('query')->where($selectwhere)->find();
            if($select){
                $where['query_id'] = $select['id'];
                $list = M('keyword')->where($where)->field('id,Keyword,baiduipc,baiduim,360pc,360m,sogoupc,sogoum,baiduipc,baiduim')->select();
                $this->assign("keyword", $keyword);
                $this->assign("header", $header);
                $this->assign("list", $list);
                $this->assign("navs", 'Keywords');
                layout('Layout/twolayout');
                $this->display();exit;
            }

            $keywordList = explode("\n", $keyword);
            $querylist['logtime'] = time();
            $querylist['kwd'] = $keyword;

            $querylist['admin_id'] = $_SESSION ["adminInfo"]['admin_id'];
            $query = M('query')->add($querylist);
            foreach ($keywordList as $k => $v) {
                trim($v);
                $datalist = array(
                    'admin_id' => $_SESSION ["adminInfo"]['admin_id'],//$_SESSION ["adminInfo"]['admin_id']
                    'Keyword' => $v,
                    'logtime' => time(),
                    'query_id' => intval($query),
                );
                $kwd = M('keyword')->add($datalist);
                $this->setworlddetails($v,$kwd);
            }

           
           $where['query_id'] = $query;
           $list = M('keyword')->where($where)->field('id,Keyword,baiduipc,baiduim,360pc,360m,sogoupc,sogoum,baiduipc,baiduim')->select();
        }else{
            
            $count = 0;
            $list = [];

        }

        $this->assign("keyword", $keyword);
        $this->assign("header", $header);
        $this->assign("list", $list);
        $this->assign("navs", 'Keywords');
        layout('Layout/twolayout');
        $this->display();
    }

    /**
     * 保存更新关键词价格
     */
    public function savePrice()
    {

        if(IS_POST){

            $price['id'] = I('post.id');
            $price['keyword'] = I('post.keyword');
            $price['baiduipc'] = I('post.baiduipc');
            $price['baiduim'] = I('post.baiduim');
            $price['360pc'] = I('post.360pc');
            $price['360m'] = I('post.360m');
            $price['sogoupc'] = I('post.sogoupc');
            $price['sogoum'] = I('post.sogoum');

            $result = M('keyword')->save($price);

            if($result){
                $this->ajaxReturn(['err_code' => 0, 'err_msg' => 'ok']);
            } else {
                $this->ajaxReturn(['err_code' => 2, 'err_msg' => 'error'.M('keyword')->getLastSql()]);
            }
        } else {
            $this->ajaxReturn(['err_code' => 1, 'err_msg' => '不能为空']);
        }
    }

    public function queryLog(){
        $search = I('search');
        if($search){
            $where['kwd'] = array('like',"%$search%");
            $this->assign("search", $search);
        }

        if(I('p')){
            $p = I('p');
        }else{
             $p = 1;
        }
        $header = C('header')['queryLog'];
        // $where['status'] = 0;
        $where['sales'] = 0;
        $count = M('query')->where($where)->count();
       


        
        $Page = new \Think\Page($count, 30);
        $Page->setConfig('theme', "%UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END%");
        $show = $Page->show(); // 分页显示输出

        $list = M('query')->where($where)->field('id,logtime,kwd')->order('id desc')->limit($Page->firstRow . ',' . $Page->listRows)->select();
        foreach ($list as $k => $v) {
            $list[$k]['logtime'] = date('Y-m-d H:i:s',$v['logtime']);
            $list[$k]['kwd'] = mb_substr($v['kwd'],0,10,'utf-8').'........';
        }

        // var_dump($show);exit;
        $show = str_replace('<div>','',$show);
        $show = str_replace('current','active',$show);
        $show = str_replace('<<<','上一页<',$show);
        $show = str_replace('>>>','>下一页',$show);
        $show = str_replace('</div>','',$show);
        // echo  htmlentities($show,ENT_QUOTES,"UTF-8");exit;
        // $show = preg_replace('//s*/', '', $show);
        if($count <= 10){
            $show = '<a href="" class="active">1</a>';
        }
        $this->assign("page", $show); // 赋值分页输出
        $this->assign("count", $count);
        $this->assign("p", $p);
        $this->assign("header", $header);
        $this->assign("list", $list);
        $this->assign("navs", 'Keywords');
        layout('Layout/twolayout');
        $this->display();
    }



    public function queryLogs(){
        $search = I('search');
        if($search){
            $where['kwd'] = array('like',"%$search%");
            $this->assign("search", $search);
        }

        if(I('p')){
            $p = I('p');
        }else{
             $p = 1;
        }
        $header = C('header')['queryLog'];
        // $where['status'] = 0;
        $where['q.sales'] = array('gt',0);
        $count = M('query')
                ->alias("q")
                ->join("left join pt_business as u on u.id=q.sales")
                ->field('u.user_name,q.id,q.logtime,q.kwd')
                ->where($where)
                ->count();
       

        $Page = new \Think\Page($count, 30);
        $Page->setConfig('theme', "%UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END%");
        $show = $Page->show(); // 分页显示输出

        $list = M('query')
                ->alias("q")
                ->join("left join pt_business as u on u.id=q.sales")
                ->field('u.user_name,q.id,q.logtime,q.kwd')
                ->where($where)
                ->order('id desc')
                ->limit($Page->firstRow . ',' . $Page->listRows)
                ->select();
        foreach ($list as $k => $v) {
            $list[$k]['logtime'] = date('Y-m-d H:i:s',$v['logtime']);
            $list[$k]['kwd'] = mb_substr($v['kwd'],0,10,'utf-8').'........';
        }

        // var_dump($show);exit;
        $show = str_replace('<div>','',$show);
        $show = str_replace('current','active',$show);
        $show = str_replace('<<<','上一页<',$show);
        $show = str_replace('>>>','>下一页',$show);
        $show = str_replace('</div>','',$show);
        // echo  htmlentities($show,ENT_QUOTES,"UTF-8");exit;
        // $show = preg_replace('//s*/', '', $show);
        if($count <= 10){
            $show = '<a href="" class="active">1</a>';
        }
        $this->assign("page", $show); // 赋值分页输出
        $this->assign("count", $count);
        $this->assign("p", $p);
        $this->assign("header", $header);
        $this->assign("list", $list);
        $this->assign("navs", 'Keywords');
        layout('Layout/twolayout');
        $this->display();
    }


    public function details(){
        $query_id = I('query_id');
        if(!$query_id){
           $this->error('信息错误');exit;
        }

        if(I('p')){
            $p = I('p');
        }else{
             $p = 1;
        }
        $header = C('header')['orders'];
        $where['query_id'] = $query_id;
        $count = M('keyword')->where($where)->count();
       

        $users = M('user')->field('user_id,user_name')->select();
        
        $Page = new \Think\Page($count, 30);
        $Page->setConfig('theme', "%UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END%");
        $show = $Page->show(); // 分页显示输出

        $list = M('keyword')->where($where)->field('id,Keyword,baiduipc,baiduim,360pc,360m,sogoupc,sogoum')->order('admin_id desc')->limit($Page->firstRow . ',' . $Page->listRows)->select();

        // var_dump($show);exit;
        $show = str_replace('<div>','',$show);
        $show = str_replace('current','active',$show);
        $show = str_replace('<<<','上一页<',$show);
        $show = str_replace('>>>','>下一页',$show);
        $show = str_replace('</div>','',$show);
        // echo  htmlentities($show,ENT_QUOTES,"UTF-8");exit;
        // $show = preg_replace('//s*/', '', $show);
        if($count <= 10){
            $show = '<a href="" class="active">1</a>';
        }
        $this->assign("page", $show); // 赋值分页输出
        $this->assign("count", $count);
        $this->assign("query_id", $query_id);
        $this->assign("p", $p);
        $this->assign("header", $header);
        $this->assign("list", $list);
        $this->assign("users", $users);
        $this->assign("navs", 'Keywords');
        layout('Layout/twolayout');
        $this->display();
    }


    public function del(){
        $del = I('del');
        if(!$del){
           $this->error('信息错误');
        }
        $where['id'] = $del;
        $list = M('keyword')->where($where)->delete();
         if($list){
            $this->success("删除成功");
        }else{
            $this->error("删除失败");
        }
    }



    public function queryList(){
       if(I('p')){
            $p = I('p');
        }else{
             $p = 1;
        }

        $search = I('search');
        if($search){
            $where['Keyword'] = array('like',"%$search%");
            $this->assign("search", $search);
        }

        $header = C('header')['orders'];
        $where['status'] = 0;
        $count = M('keyword')->where($where)->count();
       

        $Page = new \Think\Page($count, 30);
        $Page->setConfig('theme', "%UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END%");
        $show = $Page->show(); // 分页显示输出

        $list = M('keyword')->where($where)->field('id,Keyword,baiduipc,baiduim,360pc,360m,sogoupc,sogoum')->order('id desc')->limit($Page->firstRow . ',' . $Page->listRows)->select();

        // var_dump($show);exit;
        $show = str_replace('<div>','',$show);
        $show = str_replace('current','active',$show);
        $show = str_replace('<<<','上一页<',$show);
        $show = str_replace('>>>','>下一页',$show);
        $show = str_replace('</div>','',$show);
        // echo  htmlentities($show,ENT_QUOTES,"UTF-8");exit;
        // $show = preg_replace('//s*/', '', $show);
        if($count <= 10){
            $show = '<a href="" class="active">1</a>';
        }
        $this->assign("page", $show); // 赋值分页输出
        $this->assign("count", $count);
        $this->assign("p", $p);
        $this->assign("header", $header);
        $this->assign("list", $list);
        $this->assign("navs", 'Keywords');
        layout('Layout/twolayout');
        $this->display();
    }




    public function addSite(){
        if(IS_POST){
            $data = I('post.');
            // var_dump($data);exit;
            if(empty($data['query_id']) || empty($data['seo']) || empty($data['site']) || empty($data['adminadd'])  || empty($data['user_id'])){
                $this->error('请填写完整信息');exit;
            }else{
                $res['site'] = $data['site'];
                $res['ftp_ip'] = $data['ftp_ip'];
                $res['username'] = $data['username'];
                $res['adminadd'] = $data['adminadd'];
                $res['adminusername'] = $data['adminusername'];
                $res['adminpassword'] = $data['adminpassword'];
                $res['password'] = $data['password'];
                $res['query_id'] = $data['query_id'];
                $res['user_id'] = $data['user_id'];
                $res['admin_id'] = $_SESSION ["adminInfo"]['admin_id']; //$res['admin_id'] = $_SESSION ["userInfo"]['admin_id'];
                $res['seo'] = json_encode($data['seo']);

                $list = M('site')->add($res);
                $qwhere['id'] = $data['query_id'];
                $up['user_id'] = $data['user_id'];
                $up['status'] = 1;
                $query = M('query')->where($qwhere)->save($up);
                // $worlddetails = $this->worlddetails($data['query_id'],$data['site'],$data['user_id'],$data['seo']);
                $keywordList = explode(",", $data['keyList']);

                $worlddetails = $this->worlddetails($keywordList,$data['site'],$data['user_id'],$data['seo']);
                if($list && $query && $worlddetails){
                    $this->success("添加成功",U("Keywords/queryLog"));exit;
                }else{
                    $this->error("添加失败");exit;
                }
            }
        }else{
            $this->error('信息错误');exit;
        }
    }


    public function setworlddetails($keyword,$k_id){
        // $q = 1;
        // $amount = rand(2,25);
        $amount = $this->price($keyword);
        // var_dump($amount);exit;
        // for ($i=6; $i >= 1 ; $i--) {
        //     $datalist[] = array(
        //         'k_id' =>  $k_id,
        //         'seo' =>  $q,
        //         'amount' =>  $amount,
        //         'price' =>  $amount*2,
        //         'keyword' =>  $keyword,
        //         'logtime' => time(),
        //         'admin_id' => 5,//$_SESSION ["adminInfo"]['admin_id']
        //     );
        //     $q++;
        // }

        $datalist = array(
            array(
                'k_id' =>  $k_id,
                'seo' => 1,
                'amount' =>  $amount,
                'price' =>  $amount*2,
                'keyword' =>  $keyword,
                'logtime' => time(),
                'admin_id' => $_SESSION ["adminInfo"]['admin_id'],
            ),
            array(
                'k_id' =>  $k_id,
                'seo' =>  2,
                'amount' =>  $amount*1.3,
                'price' =>  $amount*1.3*2,
                'keyword' =>  $keyword,
                'logtime' => time(),
                'admin_id' => $_SESSION ["adminInfo"]['admin_id'],
            ),
            array(
                'k_id' =>  $k_id,
                'seo' =>  3,
                'amount' =>  $amount*0.5,
                'price' =>  $amount,
                'keyword' =>  $keyword,
                'logtime' => time(),
                'admin_id' => $_SESSION ["adminInfo"]['admin_id'],
            ),
            array(
                'k_id' =>  $k_id,
                'seo' =>  4,
                'amount' =>  $amount/1.6,
                'price' =>  $amount*2/1.6,
                'keyword' =>  $keyword,
                'logtime' => time(),
                'admin_id' => $_SESSION ["adminInfo"]['admin_id'],
            ),
            array(
                'k_id' =>  $k_id,
                'seo' =>  5,
                'amount' =>  $amount*0.5,
                'price' =>  $amount,
                'keyword' =>  $keyword,
                'logtime' => time(),
                'admin_id' => $_SESSION ["adminInfo"]['admin_id'],
            ),
            array(
                'k_id' =>  $k_id,
                'seo' =>  6,
                'amount' =>  $amount/1.6,
                'price' =>  $amount*2/1.6,
                'keyword' =>  $keyword,
                'logtime' => time(),
                'admin_id' => $_SESSION ["adminInfo"]['admin_id'],
            ),
        );


       
        $kwd = M('worlddetails')->addAll($datalist);
        if($kwd){
            $list = array(
                'baiduipc' => $amount*2,
                'baiduim' => $amount*2*1.3,
                '360pc' => $amount,
                '360m' => $amount*2/1.6,
                'sogoupc' => $amount,
                'sogoum' => $amount*2/1.6,
            );
            $where['id'] = $k_id;
            $res = M('keyword')->where($where)->save($list);
        }else{
            echo 'error'; exit;
        }

    }


    public function worlddetails($list,$site,$user_id,$data=array(1,2,3,4,5,6)){
    // public function worlddetails($query_id,$site,$user_id,$data=array(1,2,3,4,5,6)){
        // $where['query_id'] = $query_id;
        // $list = M('keyword')->where($where)->getField('id',true);

        $where['id'] = array('in',$list);
        $dt['status'] = 1;
        $kwdlist = M('keyword')->where($where)->setField($dt);


        $wwhere['k_id'] = array('in',$list);
        $wwhere['seo'] = array('in',$data);
        $up['site'] = $site;
        $up['user_id'] = $user_id;
        // $up['status'] = 1;
        $res = M('worlddetails')->where($wwhere)->setField($up);
        if($res && $kwdlist){
            return 1;
        }else{
            return 0;
        }
    }

    public function price($kwd){
        $today = strtotime('yesterday');
        $where['logtime'] = array('gt',$today);
        $where['Keyword'] = array('eq',$kwd);
        $where['baiduipc'] = array('neq',0);
        $price = M('keyword')->where($where)->find();
        if($price){
            $amount = $price['baiduipc']/2;
            return $amount;
        }else{
           $kwd = trim(str_replace("公司","",$kwd));
           $strlen = mb_strlen($kwd,'UTF8');
           // echo $strlen;exit;
           if($strlen == 1){
                $amount = rand(400,600);
           }elseif($strlen == 2){
                $amount = rand(250,300);
           }elseif($strlen == 3){
                $amount = rand(200,250);
           }elseif($strlen == 4){
                $amount = rand(180,230);
           }elseif($strlen == 5){
                $amount = rand(100,150);
           }elseif($strlen == 6){
                $amount = rand(90,100);
           }elseif($strlen == 7){
                $amount = rand(70,90);
           }elseif($strlen == 8){
                $amount = rand(70,85);
           }elseif($strlen == 9){
                $amount = rand(70,80);
           }elseif($strlen == 10){
                $amount = rand(70,75);
           }else{
                $amount = rand(50,70);
           }
           $amount = $amount/20;
           return $amount;
        }
    }
}